package com.shipwe.loans.ui.activity

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.os.Handler
import android.os.Looper
import android.text.SpannableString
import android.text.Spanned
import android.text.style.ForegroundColorSpan
import android.view.Gravity
import android.view.View
import android.view.animation.Animation
import android.view.animation.RotateAnimation
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.shipwe.loans.R
import com.shipwe.loans.configs.ShipweConfigs
import com.shipwe.loans.databinding.ActivityOrderDetailsBinding
import com.shipwe.loans.pro.ShipweActivity
import com.shipwe.loans.ui.adapter.OrderDetailsWalletAdapter
import com.shipwe.loans.ui.presenter.OrderDetailsPresenter
import com.shipwe.loans.ui.view.IOrderDetailsView
import com.shipwe.loans.utils.AppDensityUtil
import com.shipwe.loans.utils.decoration.LinearSpacingItemDecoration
import com.shipwe.loans.utils.dialog.AuthWalletAddDialog
import com.shipwe.loans.utils.dialog.AuthWalletDeleteDialog
import com.shipwe.loans.utils.dialog.AuthWalletOtherDialog
import com.shipwe.loans.utils.dialog.TipsDialog
import com.shipwe.loans.utils.event.AppEventData
import com.shipwe.loans.utils.event.AppEventPointType
import com.shipwe.loans.utils.helper.CustomConfigsHelper
import com.shipwe.loans.utils.shared.ShipweSharedHelper
import com.shipwe.loans.utils.shared.ShipweSharedKey
import org.json.JSONObject

/**
 * Shipwe
 * @Author wwdeng
 * @CreateTime: 2024/11/25 14:01
 * @Annotation：贷款订单详情
 */
class ActivityOrderDetails: ShipweActivity(), IOrderDetailsView {
    lateinit var binding: ActivityOrderDetailsBinding
    var presenter: OrderDetailsPresenter? = null

    //账户列表
    private var walletAdapter: OrderDetailsWalletAdapter? = null
    //埋点备注
    var eventRemark = ""

    companion object {
        private const val INTENT_KEY_PRODUCT = "product"
        private const val INTENT_KEY_TOKEN = "token"
        fun start(context: Context,pName: String, pToken: String) {
            val intent = Intent(context, ActivityOrderDetails::class.java)
            intent.putExtra(INTENT_KEY_PRODUCT, pName)
            intent.putExtra(INTENT_KEY_TOKEN, pToken)
            context.startActivity(intent)
        }
    }

    override fun getShipweRootView(): View {
        binding = ActivityOrderDetailsBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun initShipweView() {
        rootViewBinding.rootLayout.setBackgroundResource(R.drawable.page_login_bg)
        setShipweTitleBarVisibility(View.VISIBLE)
        setShipweBackBtnVisibility(View.VISIBLE)
        setShipweRightBtnRes(R.drawable.customer_black)
        setShipweTextTitleVisibility(View.GONE)

        initOrderDetailsRefreshView()
        initOrderDetailsWalletListView()
        binding.orderDetailsContent.visibility = View.GONE
        //积分
        binding.walletAddPoints.text = String.format(getString(R.string.points_add_count), CustomConfigsHelper.getShipweAddWalletPoints())
    }

    override fun initShipweListener() {
        //客服
        rootViewBinding.rootCustomer.setOnClickListener {
            showCustomerDialog(eventRemark,getProductName(),getProductToken())
            appEventPointRequestAction(AppEventPointType.CLICK.SHIPWE_CLICK_CUSTOMER,eventRemark)
        }

        //刷新订单
        binding.orderRefresh.setOnClickListener {
            binding.orderRefreshIcon.startAnimation(getRotateAnimation())
            presenter?.loadOrderDetailsStatusAction()
        }

        //添加账户
        binding.walletAdd.setOnClickListener {
            showOrderDetailsWalletAddDialog()
        }
    }

    override fun initShipweData() {
        presenter = OrderDetailsPresenter(this)
        showShipweLoading()
        presenter?.loadOrderDetailsStatusAction()
    }


    /* 初始化刷新 */
    private fun initOrderDetailsRefreshView() {
        //禁止加载
        binding.orderDetailsRefreshView.setEnableLoadMore(false)
        binding.orderDetailsRefreshView.setEnableAutoLoadMore(false)
        binding.orderDetailsRefreshView.setOnRefreshListener {
            presenter?.loadOrderDetailsStatusAction()
        }
        binding.orderDetailsRefreshView.setOnLoadMoreListener {
            binding.orderDetailsRefreshView.finishLoadMore()
        }
    }

    /**
     * 初始化Views
     */
    private fun initOrderDetailsWalletListView(){
        binding.orderWalletListView.isNestedScrollingEnabled = false
        binding.orderWalletListView.isFocusableInTouchMode = false //不需要焦点
        val topDecoration = AppDensityUtil.dp2px(12f)
        binding.orderWalletListView.addItemDecoration(LinearSpacingItemDecoration(0, 0, 0, topDecoration))
        val layoutManager = LinearLayoutManager(this)
        layoutManager.orientation = RecyclerView.VERTICAL
        binding.orderWalletListView.layoutManager = layoutManager
        walletAdapter = OrderDetailsWalletAdapter(binding.orderWalletListView)
        binding.orderWalletListView.adapter = walletAdapter!!
        binding.orderWalletListView.itemAnimator = DefaultItemAnimator()
        walletAdapter!!.setOnItemChildClickListener { _, childView, position ->
            val item = walletAdapter!!.getItem(position)
            when(childView.id){
                R.id.walletDelete -> {//删除
                    showOrderDetailsWalletDeleteDialog(item)
                }
            }
        }
    }

    /**
     * 获取查看的产品名称
     */
    override fun getProductName(): String {
        return intent.extras!!.getString(INTENT_KEY_PRODUCT).toString()
    }

    /**
     * 获取查看的产品Token
     */
    override fun getProductToken(): String {
        return intent.extras!!.getString(INTENT_KEY_TOKEN).toString()
    }

    /**
     * 刷新产品列表
     */
    override fun showOrderDetailsRefreshProductList() {
        Handler(Looper.getMainLooper()).postDelayed({
            binding.orderRefreshIcon.clearAnimation()
        },1500)
        //刷新产品列表
        publishEventData(AppEventData(AppEventData.TYPE.SHIPWE_PRODUCT_REFRESH))
    }

    /**
     * 共用Views
     */
    @SuppressLint("SetTextI18n")
    override fun showOrderDetailsCommonViews(obj: JSONObject) {
        binding.orderDetailsContent.visibility = View.VISIBLE

        binding.orderAmount.text = "${obj.optString("currency")} ${obj.optString("amount")}"
        binding.orderTerm.text = String.format(getString(R.string.order_term_value),obj.optString("days"))
    }

    /**
     * 审核中
     */
    override fun showOrderDetailsReviewingViews(obj: JSONObject) {
        eventRemark = "${getProductName()} : ${obj.optString("eventRemark")}"
        binding.orderStatusIcon.setImageResource(R.drawable.order_reviewing_icon)
        binding.orderStatus.text = getString(R.string.order_status_reviewing)
        binding.orderStatus.setTextColor(Color.parseColor("#FF2E86F6"))

        val showKey = getString(R.string.order_status_reviewing_time_value)
        val showText = String.format(getString(R.string.order_status_reviewing_time),showKey)
        val startIndex = showText.indexOf(showKey)

        val spString = SpannableString(showText)
        spString.setSpan(ForegroundColorSpan(Color.parseColor("#FFEC273A")), startIndex, startIndex + showKey.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        binding.orderStatusTips.text = spString
        binding.orderStatusDesc.text = getString(R.string.order_status_reviewing_desc)

        binding.orderRefresh.visibility = View.VISIBLE
        binding.disbursingTipsViewGroup.visibility = View.GONE
        binding.walletListViewGroup.visibility = View.VISIBLE
        binding.walletAddLayout.visibility = View.GONE

        //法语地区需要显示添加按钮
        if (ShipweConfigs.isFrench()){
            binding.walletAddLayout.visibility = View.VISIBLE
        }

        //根据配置显示公告信息
        showOrderDetailsReviewingNoticeDialog()
        //需要显示账户列表
        presenter!!.loadOrderDetailsWalletListAction()
        //需要调用评分接口
        presenter!!.loadOrderDetailsScoreCommentAction()
    }

    /**
     * 放款中
     */
    override fun showOrderDetailsDisbursingViews(obj: JSONObject) {
        eventRemark = "${getProductName()} : ${obj.optString("eventRemark")}"
        binding.orderStatusIcon.setImageResource(R.drawable.order_disbursing_icon)
        binding.orderStatus.text = getString(R.string.order_status_disbursing)
        binding.orderStatus.setTextColor(Color.parseColor("#FFF7931E"))

        binding.orderStatusTips.text = getString(R.string.order_status_disbursing_tips)
        binding.orderStatusTips.setTextColor(Color.parseColor("#FF191919"))
        binding.orderStatusDesc.text = getString(R.string.order_status_disbursing_desc)
        binding.orderStatusDesc.setTextColor(Color.parseColor("#FF858381"))

        binding.orderRefresh.visibility = View.GONE
        binding.disbursingTipsViewGroup.visibility = View.VISIBLE
        binding.walletListViewGroup.visibility = View.VISIBLE
        binding.walletAddLayout.visibility = View.GONE

        //法语地区需要显示添加按钮
        if (ShipweConfigs.isFrench()){
            binding.walletAddLayout.visibility = View.VISIBLE
        }

        //根据配置显示公告信息
        showOrderDetailsReviewingNoticeDialog()
        //需要显示账户列表
        presenter!!.loadOrderDetailsWalletListAction()
        //需要调用评分接口
        presenter!!.loadOrderDetailsScoreCommentAction()
    }

    /**
     * 已拒绝
     */
    override fun showOrderDetailsRejectedViews(obj: JSONObject) {
        eventRemark = "${getProductName()} : ${obj.optString("eventRemark")}"
        binding.orderStatusIcon.setImageResource(R.drawable.order_rejected_icon)
        binding.orderStatus.text = getString(R.string.order_status_rejected)
        binding.orderStatus.setTextColor(Color.parseColor("#FFF95D50"))

        binding.orderStatusTips.text = getString(R.string.order_status_rejected_tips)
        binding.orderStatusTips.setTextColor(Color.parseColor("#FFF95D50"))
        binding.orderStatusDesc.text = String.format(getString(R.string.order_status_rejected_desc),obj.optString("againApplyDate"))
        binding.orderStatusDesc.setTextColor(Color.parseColor("#FF858381"))

        binding.orderRefresh.visibility = View.GONE
        binding.disbursingTipsViewGroup.visibility = View.GONE
        binding.walletListViewGroup.visibility = View.GONE
    }

    /**
     * 待还款
     */
    override fun showOrderDetailsRepayViews(obj: JSONObject) {
        //跳转到待还款列表
        publishEventData(AppEventData(AppEventData.TYPE.SHIPWE_SHOW_REPAY))
        Handler(Looper.getMainLooper()).postDelayed({
            finish()
        },500)
    }

    /**
     * 只有一个账户，提示绑卡
     */
    override fun showOrderDetailsWalletOnlyOneDialog() {
        val tipsDialog = TipsDialog(this,eventRemark,object : TipsDialog.IDialogCallback{
            override fun onClick(view: View?) {
                when(view!!.id){
                    R.id.tipsConfirm -> {
                        showOrderDetailsWalletAddDialog()
                    }
                }
            }
        })
        tipsDialog.setCancelable(true)
        tipsDialog.setCanceledOnTouchOutside(true)
        tipsDialog.show()
        tipsDialog.isDoubleButton(false)
        tipsDialog.setTipsGravity(Gravity.START)
        tipsDialog.setTitleText(getString(R.string.order_details_wallet_only_one_tips))
        tipsDialog.setTipsText(getString(R.string.order_details_wallet_only_one_desc))
        tipsDialog.setBtnOkText(getString(R.string.order_details_wallet_only_one_add))
    }

    /**
     * 收款账户列表
     */
    override fun showOrderDetailsWalletList(accountList: ArrayList<JSONObject>) {
        walletAdapter!!.data = accountList

        //最多添加10个账户
        if (walletAdapter!!.itemCount >= 10){
            binding.walletAdd.isEnabled = false
        } else {
            binding.walletAdd.isEnabled = true
        }
    }

    /**
     * 添加绑卡dialog
     */
    private fun showOrderDetailsWalletAddDialog(){
        appEventPointRequestAction(AppEventPointType.CLICK.SHIPWE_CLICK_USER_ACCOUNT_ADD,eventRemark)
        val bindCardDialog = AuthWalletAddDialog(this,eventRemark,object : AuthWalletAddDialog.IDialogCallback{
            override fun onClick(view: View?) {
            }
            override fun onSubmitParams(typeObj: JSONObject, phoneNumber: String) {
                presenter!!.submitOrderDetailsWalletAddAction(phoneNumber,typeObj.optString("value"))
            }
        })
        bindCardDialog.setCancelable(true)
        bindCardDialog.setCanceledOnTouchOutside(true)
        bindCardDialog.show()
    }

    /**
     * 提示绑定另一个渠道账户
     */
    override fun showOrderDetailsWalletOtherDialog(otherInfo: JSONObject) {
        val replaceDialog = AuthWalletOtherDialog(this,eventRemark,object : AuthWalletOtherDialog.IDialogCallback{
            override fun onClick(view: View?) {
                if (view!!.id == R.id.walletOtherConfirm){//添加
                    presenter!!.submitOrderDetailsWalletAddAction(otherInfo.optString("walletMobile"),otherInfo.optString("value"), "YES")
                }
            }
        })
        replaceDialog.setCancelable(true)
        replaceDialog.setCanceledOnTouchOutside(false)
        replaceDialog.show()
        replaceDialog.setBindAccountInfo(otherInfo)
    }

    /**
     * 删除提示
     */
    private fun showOrderDetailsWalletDeleteDialog(item: JSONObject){
        item.put("walletLogo",item.optString("logo"))
        item.put("walletDesc",item.optString("name"))
        item.put("walletMobile",item.optString("account"))
        appEventPointRequestAction(AppEventPointType.CLICK.SHIPWE_CLICK_USER_ACCOUNT_DELETE,item.optString("cardId"))
        val deleteDialog = AuthWalletDeleteDialog(this,eventRemark, object : AuthWalletDeleteDialog.IDialogCallback{
            override fun onClick(view: View?) {
                if (view!!.id == R.id.walletDeleteConfirm){
                    presenter!!.deleteOrderDetailsWalletAction(item.optString("cardId"))
                }
            }
        })
        deleteDialog.setCancelable(true)
        deleteDialog.setCanceledOnTouchOutside(true)
        deleteDialog.show()
        deleteDialog.setBindAccountInfo(item)
    }

    /**
     * 审核中、放款中 根据配置显示公告Dialog
     */
    private fun showOrderDetailsReviewingNoticeDialog(){
        if (!CustomConfigsHelper.isShipweAuditNotice()){
            return
        }

        val noticeInfo = CustomConfigsHelper.getShipweAuditNoticeInfo() ?: return
        val showNum = noticeInfo.optInt("num",1)
        val completeNum = ShipweSharedHelper.getShipweSharedInt(ShipweSharedKey.SHIPWE_DIALOG_NOTICE_NUM)
        //本地记录的显示公告次数 >= 配置次数
        if (completeNum >= showNum){
            return
        }

        ShipweSharedHelper.putShipweSharedData(ShipweSharedKey.SHIPWE_DIALOG_NOTICE_NUM,completeNum+1)
        val tipsDialog = TipsDialog(this,"$eventRemark Notice",object : TipsDialog.IDialogCallback{
            override fun onClick(view: View?) {
                when(view!!.id){
                    R.id.tipsConfirm -> {
                        showOrderDetailsWalletAddDialog()
                    }
                }
            }
        })
        tipsDialog.setCancelable(true)
        tipsDialog.setCanceledOnTouchOutside(true)
        tipsDialog.show()
        tipsDialog.isDoubleButton(false)
        tipsDialog.setTipsGravity(Gravity.CENTER)
        tipsDialog.setTitleText(noticeInfo.optString("noticeTitle"))
        tipsDialog.setTipsText(noticeInfo.optString("noticeText"))
        tipsDialog.setBtnOkText(getString(R.string.click_confirm))
    }

    /**
     *旋转动画
     */
    private fun getRotateAnimation(): Animation {
        // 创建一个旋转动画对象，从当前的角度旋转到指定的角度，持续时间为1000毫秒
        val rotateAnimation = RotateAnimation(0F, 360f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f)
        rotateAnimation.setDuration(1000L) // 设置动画持续时间
//        rotateAnimation.fillAfter = false // 动画执行完后保持结束状态
        rotateAnimation.isFillEnabled = true;
        rotateAnimation.fillBefore = false;
        rotateAnimation.setRepeatCount(Animation.INFINITE); // 设置动画重复次数
        return rotateAnimation
    }

    override fun dismissShipweLoading() {
        super.dismissShipweLoading()
        binding.orderDetailsRefreshView.finishRefresh()
    }

    override fun onStart() {
        super.onStart()
        eventRemark = "${getProductName()} Details Page"
        appEventPointRequestAction(AppEventPointType.PAGE.SHIPWE_PAGE_LOAN_DETAILS_START,eventRemark)
    }

    override fun onDestroy() {
        super.onDestroy()
        appEventPointRequestAction(AppEventPointType.PAGE.SHIPWE_PAGE_LOAN_DETAILS_END,eventRemark)
    }
}